package com.hwtx.form;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Autowired
    private ConfigurableApplicationContext context;

    public void registerOrderService() {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

        // 创建 GenericBeanDefinition
        BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(OrderService.class);

        // 设置 scope 为 singleton（默认）
        definition.setScope("singleton");

        // 添加属性值
        definition.addPropertyValue("name", "Sample Name");

        // 注册 Bean 定义
        beanFactory.registerBeanDefinition("orderService", definition.getBeanDefinition());

        // 触发依赖注入
        context.getAutowireCapableBeanFactory().autowireBeanProperties(
            context.getBean("orderService"),
            org.springframework.beans.factory.config.AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
            true
        );
    }
}